//
//  HHSelectUserViewController.m
//  HHChatKit
//
//  Created by Henry on 2021/8/20.
//

#import "HHSelectUserViewController.h"
#import <HHTool/HHTool.h>
#import <SCIndexView/UITableView+SCIndexView.h>
#import "HHSelectUserSearchResultView.h"
#import "HHSelectUserTableViewCell.h"
#import "UIImageView+HHChat.h"
#import "HHChatConfiguration.h"
#import "HHResources.h"
#import "HHChatHelper.h"
#import "HHSectionUtil.h"

@interface HHSelectUserViewController () <UITableViewDataSource, UITableViewDelegate, UITextFieldDelegate>

@property (nonatomic, strong) UIButton *rightItem;
@property (nonatomic, strong) UITextField *textField;
@property (nonatomic, strong) UIView *leftView;
@property (nonatomic, strong) UIScrollView *leftScrollView;
@property (nonatomic, strong) UIView *lineView;
@property (nonatomic, strong) HHSelectUserSearchResultView *searchResultView;

@property (nonatomic, strong) NSMutableArray *sectionArray;
@property (nonatomic, strong) NSMutableArray *sectionTitlesArray;
@property (nonatomic, strong) NSMutableArray *sectionIndexTitles;

@property (nonatomic, strong) NSMutableArray <HHSelectUserModel *> *leftDatas;
@property (nonatomic, strong) NSMutableArray <UIImageView *> *leftImageViews;

@property (nonatomic, strong) NSMutableArray *searchDataArray;

@property (nonatomic, assign) BOOL isSearch;

@end

static NSString * const cellIdentifier = @"UITableViewCell";
static NSString * const userIdentifier = @"HHSelectUserTableViewCell";

@implementation HHSelectUserViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor hh_whiteColor];
    self.dataArray = [NSMutableArray array];
    self.leftDatas = [NSMutableArray array];
    self.leftImageViews = [NSMutableArray array];
    [self setupUI];
}

- (void)setupUI {
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:self.rightItem];
    [self.view addSubview:self.textField];
    [self.view addSubview:self.lineView];
    [self.view addSubview:self.tableView];
    [self.view addSubview:self.searchResultView];
}

- (void)viewDidLayoutSubviews {
    [super viewDidLayoutSubviews];
    self.textField.frame = CGRectMake([HHChatHelper safeAreaInset].left, [HHChatHelper statusNavHeight], self.view.width-[HHChatHelper safeAreaInset].left-[HHChatHelper safeAreaInset].right, 56);
    self.lineView.frame = CGRectMake(self.textField.left, self.textField.bottom, self.textField.width, 1);
    self.tableView.frame = CGRectMake(self.textField.left, self.lineView.bottom, self.textField.width, self.view.height-self.lineView.bottom);
    self.searchResultView.frame = self.tableView.frame;
}

#pragma mark - Public

- (void)reloadSelectData {
    for (HHSelectUserModel *model in self.dataArray) {
        if (model.isSelected && !model.unable) {
            [self.leftDatas addObject:model];
            [self.leftImageViews addObject:[self createItemImageView:model]];
        }
    }
    [self updateLeftView];
}

- (void)reloadData {
    NSArray *arr = [HHSectionUtil tableSection:self.dataArray];
    if (arr.count < 2) {
        return;
    }
    NSMutableArray *titleArray = [arr[1] mutableCopy];
    self.sectionArray = [arr[0] mutableCopy];
    self.sectionTitlesArray = [titleArray mutableCopy];
    
    if (self.headerArray.count > 0) {
        [self.sectionArray insertObject:self.headerArray atIndex:0];
        [self.sectionTitlesArray insertObject:@"" atIndex:0];
        self.tableView.sc_startSection = 1;
    }
    self.sectionIndexTitles = titleArray.mutableCopy;
    if (self.hasIndexSearch) {
        [self.sectionIndexTitles insertObject:UITableViewIndexSearch atIndex:0];
    }
    
    [self.tableView reloadData];
    self.tableView.sc_indexViewDataSource = self.sectionIndexTitles;
}

- (NSArray<HHSelectUserModel *> *)getSelectData {
    return self.leftDatas;
}

- (NSArray<NSString *> *)getSelectUserIds {
    NSMutableArray *arr = @[].mutableCopy;
    for (HHSelectUserModel *model in self.leftDatas) {
        [arr addObject:model.userId];
    }
    return arr;
}

- (void)didSelectHeaderAtIndex:(NSInteger)index {}

- (void)onClickDone:(UIButton *)sender {
    if (self.doneCallback) {
        self.doneCallback(self.leftDatas);
    }
}

- (void)textFieldDidChanged:(UITextField *)textField {
    UITextRange *markedTextRange = textField.markedTextRange;
    // 如果存在待选文字记录，则暂不处理 markedTextRange == nil说明不存在待选文字
    if (markedTextRange == nil) {
        [self selectList];
    }
    if (textField.text.length == 0) {
        self.isSearch = NO;
    } else {
        self.isSearch = YES;
    }
}

- (void)selectList {
    NSString *text = self.textField.text;
    // 去掉前后空格
    text = [text stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
    if (text.length == 0) {
        self.searchDataArray = self.dataArray.mutableCopy;
        return;
    }
    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"account CONTAINS[c] %@ || remark CONTAINS[c] %@ || name CONTAINS[cd] %@", text, text, text, text];
    NSArray *searchResultArray = [self.dataArray filteredArrayUsingPredicate:predicate];
    self.searchDataArray = searchResultArray.mutableCopy;
    self.isSearch = YES;
}

- (void)setIsSearch:(BOOL)isSearch {
    _isSearch = isSearch;
    if (isSearch) {
        self.searchResultView.hidden = NO;
        [self.searchResultView reloadData:self.searchDataArray];
        self.tableView.sc_indexViewDataSource = nil;
    } else {
        [self.searchDataArray removeAllObjects];
        self.searchResultView.hidden = YES;
        self.textField.text = @"";
        self.tableView.sc_indexViewDataSource = self.sectionIndexTitles;
    }
}

#pragma mark - UITextFieldDelegate

- (BOOL)textFieldShouldReturn:(UITextField *)textField {
    [self selectList];
    return YES;
}

#pragma mark - UITableViewDataSource, UITableViewDelegate

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return self.sectionTitlesArray.count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return [self.sectionArray[section] count];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (self.headerArray.count > 0 && indexPath.section == 0) {
        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
        cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
        cell.textLabel.text = self.headerArray[indexPath.row];
        return cell;
    }
    HHSelectUserTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:userIdentifier];
    HHSelectUserModel *model = self.sectionArray[indexPath.section][indexPath.row];
    cell.model = model;
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    if (self.headerArray.count > 0) {
        if (section == 0) {
            return 0;
        }
    }
    return 25;
}

- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
    return self.sectionTitlesArray[section];
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView deselectRowAtIndexPath:indexPath animated:NO];
    if (self.headerArray.count > 0 && indexPath.section == 0) {
        [self didSelectHeaderAtIndex:indexPath.row];
        return;
    }
    
    HHSelectUserModel *model = self.sectionArray[indexPath.section][indexPath.row];
    if (model.unable) {
        return;
    }
    
    HHSelectUserTableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
    cell.checked = !cell.checked;
    model.isSelected = cell.checked;
    if (cell.checked) {
        [self.leftDatas addObject:model];
        [self.leftImageViews addObject:[self createItemImageView:model]];
    } else {
        NSInteger removeIndex = -1;
        for (NSInteger i = 0; i < self.leftDatas.count; ++i) {
            HHSelectUserModel *sModel = [self.leftDatas objectAtIndex:i];
            if ([sModel.userId isEqualToString:model.userId]) {
                removeIndex = i;
                break;
            }
        }
        if (removeIndex >= 0) {
            [self.leftDatas removeObjectAtIndex:removeIndex];
            [self.leftImageViews removeObjectAtIndex:removeIndex];
        }
    }
    [self updateLeftView];
}

- (UIImageView *)createItemImageView:(HHSelectUserModel *)model {
    UIImageView *imageView = [[UIImageView alloc] init];
    [imageView hh_setAvatarWithUrl:model.portrait ID:model.userId name:model.name];
    return imageView;
}

- (void)updateLeftView {
    for (UIView *view in self.leftScrollView.subviews) {
        [view removeFromSuperview];
    }
    if (self.leftDatas.count == 0) {
        [self setRightItem:GetHCLocalizableString(@"Done") enable:NO];
        self.textField.leftView = self.leftView;
        return;
    }
    
    self.textField.leftView = self.leftScrollView;
    
    CGFloat itemWidth = 50;
    CGFloat textMinWidth = 100;
    CGFloat leftMargin = 10;
    
    self.leftScrollView.contentSize = CGSizeMake(50*self.leftDatas.count + leftMargin, 56);
    
    CGFloat maxWidth = self.view.frame.size.width - textMinWidth;
    
    CGFloat ww = MIN(itemWidth * self.leftDatas.count + leftMargin, maxWidth);
    self.leftScrollView.frame = CGRectMake(0, 0, ww, 56);

    for (int i = 0; i < self.leftImageViews.count; ++i) {
        UIImageView *imageView = self.leftImageViews[i];
        [self.leftScrollView addSubview:imageView];
        imageView.frame = CGRectMake(i * itemWidth + leftMargin, 8, 40, 40);
        [imageView hh_cornerRadius:[HHChatConfiguration shareInstance].defaultAvatarCorner];
    }
    
    CGFloat ss = itemWidth * self.leftDatas.count + leftMargin - maxWidth;
    
    if (ss > 0) {
        [self.leftScrollView setContentOffset:CGPointMake(ss, 0) animated:YES];
    }
    
    [self setRightItem:[NSString stringWithFormat:@"%@(%ld)", GetHCLocalizableString(@"Done"), self.leftDatas.count] enable:YES];

}

- (void)setRightItem:(NSString *)title enable:(BOOL)enable {
    [self.rightItem setTitle:title forState:UIControlStateNormal];
    self.rightItem.enabled = enable;
    if (enable) {
        [self.rightItem setBackgroundColor:[UIColor hh_colorWithString:@"#1ECB95"]];
        [self.rightItem setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    } else {
        [self.rightItem setBackgroundColor:[UIColor hh_colorWithString:@"#999999"]];
        [self.rightItem setTitleColor:[UIColor hh_colorWithString:@"#666666"] forState:UIControlStateNormal];
    }
    
    CGSize size = [title hh_textSizeInFont:self.rightItem.titleLabel.font];
    self.rightItem.frame = CGRectMake(0, 0, size.width+24, MIN(size.height+12, [HHChatHelper navBarHeight]));
}

- (void)selectedUserModel:(HHSelectUserModel *)userModel fromSearch:(BOOL)fromSearch {
    NSInteger selectedIndex = -1;
    for (NSInteger i = 0; i < self.leftDatas.count ; ++ i) {
        HHSelectUserModel *model = self.leftDatas[i];
        if ([model.userId isEqualToString:userModel.userId]) {
            selectedIndex = i;
            break;
        }
    }
    
    if (selectedIndex == -1) {
        // 添加
        [self.leftDatas addObject:userModel];
        [self.leftImageViews addObject:[self createItemImageView:userModel]];
        
    } else {
        if (!userModel.isSelected) {
            [self.leftDatas removeObjectAtIndex:selectedIndex];
            [self.leftImageViews removeObjectAtIndex:selectedIndex];
        }
    }
    
    // 联系人
    for (int k = 0; k < self.dataArray.count; ++ k) {
        HHSelectUserModel *model = self.dataArray[k];
        if ([model.userId isEqualToString:userModel.userId]) {
            if (fromSearch) {
                [self reloadData];
            } else {
                if (model.isSelected != userModel.isSelected) {
                    model.isSelected = userModel.isSelected;
                    [self reloadData];
                }
            }
            break;
        }
    }
    [self updateLeftView];
}
    
#pragma mark - Getters

- (UIButton *)rightItem {
    if (!_rightItem) {
        _rightItem = [UIButton buttonWithType:UIButtonTypeCustom];
        _rightItem.layer.cornerRadius = 5;
        _rightItem.layer.masksToBounds = YES;
        [self setRightItem:GetHCLocalizableString(@"Done") enable:NO];
        [_rightItem addTarget:self action:@selector(onClickDone:) forControlEvents:UIControlEventTouchUpInside];
    }
    return _rightItem;
}

- (UITextField *)textField {
    if (!_textField) {
        _textField = [[UITextField alloc] init];
        _textField.backgroundColor = [UIColor hh_colorWithLightColor:[UIColor whiteColor] darkColor:[UIColor blackColor]];
        _textField.placeholder = GetHCLocalizableString(@"Search");
        _textField.leftViewMode = UITextFieldViewModeAlways;
        _textField.leftView = self.leftView;
        _textField.returnKeyType = UIReturnKeySearch;
        _textField.delegate = self;
         [_textField addTarget:self action:@selector(textFieldDidChanged:) forControlEvents:UIControlEventEditingChanged];
    }
    return _textField;
}

- (UIView *)leftView {
    if (!_leftView) {
        _leftView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 50, 56)];
        UIImageView *image = [[UIImageView alloc] initWithImage:[HHResources getImageFromMessage:@"icon_search"]];
        image.contentMode = UIViewContentModeCenter;
        image.frame = CGRectMake(0, 0, 50, 56);
        [_leftView addSubview:image];
    }
    return _leftView;
}

- (UIScrollView *)leftScrollView {
    if (!_leftScrollView) {
        _leftScrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 0, 50, 56)];
        _leftScrollView.backgroundColor = [UIColor hh_colorWithLightColor:[UIColor whiteColor] darkColor:[UIColor blackColor]];
    }
    return _leftScrollView;;
}

- (UIView *)lineView {
    if (!_lineView) {
        _lineView = [[UIView alloc] init];
        _lineView.backgroundColor = HHChatConfiguration.shareInstance.lineColor;
    }
    return _lineView;
}

- (UITableView *)tableView {
    if (!_tableView) {
        UITableView *tableView = [[UITableView alloc] initWithFrame:self.view.bounds style:UITableViewStylePlain];
        tableView.delegate = self;
        tableView.dataSource = self;
        tableView.tableFooterView = [[UIView alloc] init];
        tableView.backgroundColor = self.view.backgroundColor;
        tableView.estimatedRowHeight = 0;
        tableView.estimatedSectionHeaderHeight = 0;
        tableView.estimatedSectionFooterHeight = 0;
        tableView.rowHeight = [HHSelectUserTableViewCell viewHeight];
        [tableView registerClass:[HHSelectUserTableViewCell class] forCellReuseIdentifier:userIdentifier];
        [tableView registerClass:[UITableViewCell class] forCellReuseIdentifier:cellIdentifier];

        tableView.keyboardDismissMode = UIScrollViewKeyboardDismissModeOnDrag;
        
        SCIndexViewConfiguration *configuration = [SCIndexViewConfiguration configuration];
        configuration.indexItemsSpace = 5;
        tableView.sc_indexViewConfiguration = configuration;

        _tableView = tableView;
    }
    return _tableView;
}

- (HHSelectUserSearchResultView *)searchResultView {
    if (!_searchResultView) {
        _searchResultView = [[HHSelectUserSearchResultView alloc] init];
        _searchResultView.forceSelect = YES;
        _searchResultView.hidden = YES;
        __weak typeof(self) ws = self;
        _searchResultView.selectedCallback = ^(HHSelectUserModel * _Nonnull userModel) {
            ws.isSearch = NO;
            [ws.searchDataArray removeAllObjects];
            ws.searchResultView.hidden = YES;
            [ws selectedUserModel:userModel fromSearch:YES];
        };
    }
    return _searchResultView;
}

@end
